package com.tean.book

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.webkit.*
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import com.tean.book.databinding.ActivityWebviewX5Binding
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebViewClient

/**
 * Created by Administrator on 2016/6/2.
 */
class MainActivity : BaseVBActivity<ActivityWebviewX5Binding>(R.layout.activity_webview_x5) {
    private var url: String? = "file:///android_asset/book/index.html"

    override fun initView() {
        initBackBtn()
//        initData()
        initTitle()
        initCollect()
        initWebView()
    }

    override fun initBackBtn() {
        findViewById<View>(R.id.back_btn).visibility = View.VISIBLE
        findViewById<View>(R.id.back_btn).setOnClickListener {
            if(mBinding.commonWebView.canGoBack()){
                mBinding.commonWebView.goBack()
            }else{
                onBackPressed()
            }
        }
    }

    override fun initData() {
    }

    override fun onResume() {
        super.onResume()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        QbSdk.initX5Environment(this, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {}
            override fun onViewInitFinished(b: Boolean) {
                //true表示成功加载x5内核，false表示加载失败，使用内置的webview
//                Log.i(BaseVBActivity.TAG, "onViewInitFinished: $b")
            }
        })

        mBinding.commonWebView.settings.blockNetworkImage = false
        mBinding.commonWebView.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN


        // 获取网络设置

        // 获取网络设置
        val webSettings: WebSettings = mBinding.commonWebView.settings
        webSettings.mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
        webSettings.setGeolocationEnabled(true)// 启用地理定位
        webSettings.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        //启用应用缓存

        //启用应用缓存
        webSettings.setAppCacheEnabled(true)
        webSettings.defaultTextEncodingName = "utf-8"
        webSettings.databaseEnabled = true
        webSettings.javaScriptEnabled = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.allowFileAccess = true

        webSettings.useWideViewPort = true
        webSettings.builtInZoomControls = true

        //开启DOM缓存，qq
        //开启DOM缓存，qq
        webSettings.domStorageEnabled = true
        //适应屏幕
        //适应屏幕
        webSettings.loadWithOverviewMode = true
        //这个一定要设置为false
        //这个一定要设置为false
        webSettings.setSupportMultipleWindows(false)
        webSettings.javaScriptCanOpenWindowsAutomatically = true

        if (mBinding.commonWebView.x5WebViewExtension != null) { //视频全屏的相关配置
//            Toast.makeText(this, "如果弹出该Toast就能全屏", Toast.LENGTH_SHORT).show()
            //没有弹出的情况下全屏按钮是灰色的不可点击
            val data = Bundle()
            data.putBoolean("standardFullScreen", false) // true表示标准全屏，false表示X5全屏；不设置默认false，
            data.putBoolean("supportLiteWnd", true) // false：关闭小窗；true：开启小窗；不设置默认true，
            data.putInt("DefaultVideoScreen", 1) // 1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
            mBinding.commonWebView.x5WebViewExtension.invokeMiscMethod("setVideoParams", data)
        }

        //加载网页

        //加载网页
//        mBinding.commonWebView.loadDataWithBaseURL("", htmlContent, "text/html", "UTF-8", "")
        mBinding.commonWebView.loadUrl(url)
        mBinding.commonWebView.webViewClient = MyWebViewClient()
    }

    /**
     * //不使用缓存
     */
    private fun clearWebView() {
        deleteDatabase("WebView.db")
        deleteDatabase("WebViewCache.db")
        mBinding.commonWebView.clearHistory()
        mBinding.commonWebView.clearFormData()
    }

    override fun onDestroy() {
        mBinding.commonWebView.destroy()
        super.onDestroy()
    }


    fun dismissDialog() {}
    fun toast() {}

    // Web视图
    private inner class MyWebViewClient : WebViewClient() {
        override fun onPageStarted(p0: com.tencent.smtt.sdk.WebView?, p1: String?, p2: Bitmap?) {
            super.onPageStarted(p0, p1, p2)
        }
        override fun onPageFinished(p0: com.tencent.smtt.sdk.WebView?, p1: String?) {
            super.onPageFinished(p0, p1)
        }
        override fun onPageCommitVisible(p0: com.tencent.smtt.sdk.WebView?, p1: String?) {
            super.onPageCommitVisible(p0, p1)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) { // 按下的如果是BACK，同时没有重复
            onBackPressed()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    companion object {
        private val TAG = MainActivity::class.java.simpleName
        fun startWebView(mContext: Context, title: String?, url: String, direction: Int) {
            if (url.trim { it <= ' ' }.length > 1) {
                val intent = Intent()
                intent.setClass(mContext, MainActivity::class.java)
                intent.putExtra(WebViewUtils.EXTRA_TITLE, title)
                intent.putExtra(WebViewUtils.EXTRA_URL, url)
                intent.putExtra(WebViewUtils.EXTRA_DIRECTION, direction)
                mContext.startActivity(intent)
            }
        }
    }
}